import {getConfig, getCurRoute} from '../utils/util';

// 重新登录流程
function reLogin () {
  wx.showToast ({
    title: '登录失效，请重新登录',
    icon: 'none',
  });
  // 清除token
  wx.removeStorageSync ('token');
  wx.removeStorageSync ('userInfo');
  const redirect = getCurRoute ();
  setTimeout (() => {
    wx.redirectTo ({
      url: `/pages/login/index?redirect=${encodeURIComponent (redirect)}`,
    });
  }, 1000);
}

export default function request (params) {
  const baseUrl = getConfig ('baseUrl');
  const token = wx.getStorageSync ('token');
  return new Promise ((resolve, reject) => {
    if (params.needLogin !== false && !token) {
      // 需要登录
      wx.showToast ({
        title: '请先登录',
        icon: 'none',
      });
      // 清除token
      wx.removeStorageSync ('openId');
      wx.removeStorageSync ('nickName');
      wx.removeStorageSync ('avatarUrl');
      wx.removeStorageSync ('userInfo');
      setTimeout (() => {
        wx.switchTab ({
          url: `/pages/mine/mine`,
        });
      }, 1000);
      return reject ('请先登录');
    }
    let contentType = 'application/x-www-form-urlencoded';
    if (params.body) {
      contentType = 'application/json';
    }
    const header = {
      'accept': 'application/json',
      'content-type': contentType,
      token: token,
    };
    let showLoading = false;
    if (params.loading !== false) {
      showLoading = true;
      wx.showLoading ({
        title: params.loadingText || '加载中',
        mask: true,
      });
    }
    let timeout = 20000;
    if (params.timeout > 0) {
      timeout = params.timeout;
    }
    wx.request ({
      url: `${baseUrl}${params.url}`,
      timeout,
      header,
      data: params.data || {},
      method: params.method || 'GET',
      success: res => {
        if (showLoading) {
          wx.hideLoading ();
        }
        // 小程序
        if (params.app !== true) {
          switch (res.data.code) {
            case 200:
              return resolve (res.data);
            case 20019:
            case 20020:
            case 20021:
              if (params.needLogin === false) {
                return;
              }
              reLogin ();
              break;
            default:
              if (params.toast !== false) {
                wx.showToast ({
                  title: res.data.msg || '服务器开小差了',
                  icon: 'none',
                });
              }
              return reject (res.data);
          }
          return;
        }
        return;
      },
      fail: res => {
        if (showLoading) {
          wx.hideLoading ();
        }
        wx.showToast ({
          title: '服务器开小差了',
          icon: 'none',
        });
        return reject (res);
      },
      complete: res => {
        if (wx.getAccountInfoSync ().miniProgram.envVersion == 'trial') {
          // 体验版打印结果
          console.log (res);
        }
      },
    });
  });
}
